package com.wbao.dianniu.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CanDoBlankGridView;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.SpanTextView;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.listener.IQuestDelListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.update.QaDataChangeManager;
import com.wbao.dianniu.manager.QuestDelManager;
import com.wbao.dianniu.manager.QuestGoodManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.List;


public class QAInfoAdapter extends BaseAdapter implements IQuestDelListener {
    private Context mContext;
    private List<QaResponse> mList;
    private LayoutInflater mInflater;
    private GridHolder holder;
    //是否有热门置顶显示
    private int topCounts = 0;
    private QuestDelManager manager;
    private int position;

    public QAInfoAdapter(Context ctx) {
        mContext = ctx;
        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mList = new ArrayList<QaResponse>();
        manager = new QuestDelManager(mContext);
        manager.addQuestDelListener(this);
    }

    /**
     * 清空数据
     */
    public void cleanData() {
        if (null != mList) {
            mList.clear();
        }
        topCounts = 0;
    }

    /**
     * 向前追加数据
     *
     * @param list
     */
    public void addForwardList(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }
        mList.addAll(0, list);
    }

    /**
     * 向后追加数据
     *
     * @param list
     */
    public void addBackwardList(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }
        for (int i = 0; i < list.size(); i++) {
            mList.add(list.get(i));
        }
    }

//    public void addFootDataList(List<QaResponse> list) {
//
//    }

    public void setData(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }
        mList = list;
    }

    public List<QaResponse> getList() {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }
        return mList;
    }

    /**
     * 最后一条数据的ID，倒序排列，这条数据最老
     *
     * @return
     */
    public Integer getLastId() {
        if (null == mList || 0 == mList.size()) {
            return null;
        }
        return mList.get(mList.size() - 1).id;
    }

    /**
     * 第一条数据的ID，倒序排列，这条数据最新
     *
     * @return
     */
    public Integer getFirstId() {
        if (null == mList || 0 == mList.size()) {
            return null;
        }
        return mList.get(0).id;
    }

    /**
     * 数据是否置顶显示处理方法，主要处理是否置顶文字的显示和置顶与非置顶之间的分割线显示
     */
    public void processList() {
        topCounts = 0;
        for (int i = 0; i < mList.size(); i++) {
            if (1 == mList.get(i).top) {
                topCounts++;
            }
        }
        if (topCounts > 0) {
            mList.get(0).isTopShow = 1;
            mList.get(topCounts - 1).isLineShow = 1;
        }
    }

    @Override
    public int getCount() {
        if (null == mList)
            return 0;
        else
            return mList.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int index, View convertView, ViewGroup parent) {
        holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.qa_list_item, null);
            holder = new GridHolder();
            holder.isTopTV = (TextView) convertView.findViewById(R.id.isTop_show);
            holder.headIV = (ImageView) convertView.findViewById(R.id.user_head);
            holder.nameTV = (TextView) convertView.findViewById(R.id.user_name);
            holder.sexIV = (ImageView) convertView.findViewById(R.id.user_sex);
            holder.labelTV = (TextView) convertView.findViewById(R.id.user_label);
            holder.addV = (ImageView) convertView.findViewById(R.id.add_v_iv);
            holder.contentTV = (SpanTextView) convertView.findViewById(R.id.qa_content_tv);

            holder.forwardTV = (TextView) convertView.findViewById(R.id.include_forward_tv);
            holder.praiseTV = (TextView) convertView.findViewById(R.id.include_praise_tv);
            holder.commentTV = (TextView) convertView.findViewById(R.id.include_answer_tv);
            holder.deleteTV = (TextView) convertView.findViewById(R.id.include_delete_tv);
            holder.visitorTV = (TextView) convertView.findViewById(R.id.include_visitor_tv);

            holder.headInfoLayout = (LinearLayout) convertView.findViewById(R.id.user_head_layout);
            holder.gridview = (CanDoBlankGridView) convertView.findViewById(R.id.noScroollGridView);
            convertView.setTag(holder);
        } else {
            holder = (GridHolder) convertView.getTag();
        }
        final QaResponse resp = mList.get(index);
        boolean isNeed = false;
        if (null != resp) {
            PictureDownloadUtils.displayHeadImage(mContext, holder.headIV, resp.headPic);
            holder.nameTV.setText(resp.realName == null ? "" : resp.realName);
            holder.labelTV.setText(resp.label == null ? "" : resp.label);
            Utils.showSex(mContext, resp.userInfo.sex, holder.sexIV);
            Utils.showAuth(resp.userInfo, holder.addV);

            Utils.showSpanContent(mContext, resp.content, resp.noticeJson, holder.contentTV);
            if (1 == resp.isTopShow) {
                holder.isTopTV.setVisibility(View.VISIBLE);
            } else {
                holder.isTopTV.setVisibility(View.GONE);
            }
            // 删除按钮
            if (resp.accountId == GlobalContext.getAccountId()) {
                holder.deleteTV.setVisibility(View.VISIBLE);
            } else {
                holder.deleteTV.setVisibility(View.INVISIBLE);
            }
            //是否点赞
            if (0 == resp.isGood) {
                Drawable right_draw = mContext.getResources().getDrawable(R.drawable.click_praise_icon_nor);
                right_draw.setBounds(0, 0, right_draw.getMinimumWidth(), right_draw.getMinimumHeight());
                holder.praiseTV.setCompoundDrawables(right_draw, null, null, null);
            } else {
                Drawable right_draw = mContext.getResources().getDrawable(R.drawable.click_praise_icon_sel);
                right_draw.setBounds(0, 0, right_draw.getMinimumWidth(), right_draw.getMinimumHeight());
                holder.praiseTV.setCompoundDrawables(right_draw, null, null, null);
            }
            Utils.showPriseCounts(resp.goodCount, holder.praiseTV);
            Utils.showPriseCounts(resp.answerCount, holder.commentTV);
            Utils.showVisitorCounts(resp.visitorCount, holder.visitorTV);
//            Utils.showPriseCounts(resp.forwardCount, holder.forwardTV);

            DetailListener dListener = new DetailListener(resp);
            //添加监听事件
            holder.headIV.setOnClickListener(dListener);
            holder.headInfoLayout.setOnClickListener(dListener);
            holder.contentTV.setOnClickListener(dListener);
            holder.forwardTV.setOnClickListener(new ShareListener(resp));
            holder.commentTV.setOnClickListener(dListener);
            holder.praiseTV.setOnClickListener(new praiseListener(index, resp.isGood, resp.goodCount));
            holder.deleteTV.setOnClickListener(new DeleteListener(index, resp.id));

            if (TextUtils.isEmpty(resp.questImgs)) {
                holder.gridview.setVisibility(View.GONE); // 没有图片资源就隐藏GridView
            } else {
                ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
                holder.gridview.setVisibility(View.VISIBLE);
                //通过图片张数 设置gridview的高度
                double multiple = Math.ceil((float) imageUrls.size() / GlobalContext.NUMCOLUMNS);

                int height = (int) (Utils.dip2px(mContext, 80) * multiple + (multiple - 1) * Utils.dip2px(mContext, 10));
                int width = 0;
                if (multiple >= 1) {
                    width = Utils.dip2px(mContext, 80) * GlobalContext.NUMCOLUMNS + (GlobalContext.NUMCOLUMNS - 1) * Utils.dip2px(mContext, 5);
                } else {
                    width = Utils.dip2px(mContext, 80) * imageUrls.size() + (imageUrls.size() - 1) * Utils.dip2px(mContext, 5);
                }
                width = width + Utils.dip2px(mContext, 10);// 加上pendingLeft 10dp
                LayoutParams lp = new LayoutParams(width, height);
                holder.gridview.setLayoutParams(lp);
                holder.gridview.setAdapter(new NoScrollGridAdapter(mContext, imageUrls));
                // 点击回帖九宫格，查看大图
                holder.gridview.setOnItemClickListener(new MyItemClickListener(imageUrls));
                holder.gridview.setOnTouchInvalidPositionListener(new CanDoBlankGridView.OnTouchInvalidPositionListener() {

                    @Override
                    public boolean onTouchInvalidPosition(int motionEvent) {
                    /*当返回false的时候代表交由父级控件处理，当return true的时候表示你已经处理了该事件并不让该事件再往上传递。为了出发listview的item点击就得返回false了*/
                        return false;
                    }
                });
            }
        }

        return convertView;
    }

    class DeleteListener implements OnClickListener {

        private int index;
        private int questId;

        public DeleteListener(int position, int questId) {
            this.index = position;
            this.questId = questId;
        }

        @Override
        public void onClick(View v) {
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
            builder.setTitle("确认删除该条问答吗？");
            builder.setPositiveButton(mContext.getResources().getString(R.string.confirm),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            position = index;
                            manager.deleteQuest(GlobalContext.getAccountId(), questId);
                        }
                    });
            builder.setNegativeButton(mContext.getResources().getString(R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();
        }

    }

    @Override
    public void onQuestDelFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onQuestDelSuccess() {
        // 通知其它界面数据改变
        QaDataChangeManager qaDataChangeManager = QaDataChangeManager.getInstance();
        qaDataChangeManager.notifyRemove(mList.get(position).id);
    }

    class MyItemClickListener implements OnItemClickListener {

        private ArrayList<String> url;

        public MyItemClickListener(ArrayList<String> url) {
            this.url = url;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // TODO Auto-generated method stub
            //弹出图片查看按钮
            imageBrower(position, url);
        }

    }


    /**
     * 打开图片查看器
     *
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Utils.imageBrower(mContext, position, urls2);
    }


    /**
     * 点赞
     *
     * @author yejianjun
     */
    class praiseListener implements OnClickListener {
        private int isGood;
        private int goodCount;
        private int position;

        public praiseListener(int position, int isGood, int goodCount) {
            this.position = position;
            this.isGood = isGood;
            this.goodCount = goodCount;
        }

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.include_praise_tv) {
                if (isGood == 0) {
                    isGood = 1;
                    goodCount++;
                } else {
                    isGood = 0;
                    goodCount--;
                }
                goodclick(mList.get(position).id);
                QaDataChangeManager qaDataChangeManager = QaDataChangeManager.getInstance();
                qaDataChangeManager.priseNotify(mList.get(position).id, isGood, goodCount);
            }
        }

    }

    private void goodclick(int questId) {
        QuestGoodManager manager = new QuestGoodManager(mContext);
        manager.good(GlobalContext.getAccountId(), questId);
        // 通知界面点赞数变更  notifyQaChanged(questId,isGood);

    }

    /**
     * 分享
     */
    private class ShareListener implements OnClickListener {

        private QaResponse resp;

        public ShareListener(QaResponse resp) {
            this.resp = resp;
        }

        @Override
        public void onClick(View v) {
            String imageUrl = null;
            if (TextUtils.isEmpty(resp.questImgs)) {
                imageUrl = GlobalContext.cdndownUrl + resp.headPic;
            } else {
                ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
                imageUrl = imageUrls.get(0);
            }
            ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
            shareSDKManager.showShare(mContext, resp.content, 1, imageUrl, resp.id);
        }

    }


    /**
     * 问题详情、点击头像、点击点赞。点击回复等
     */
    private class DetailListener implements OnClickListener {
        private QaResponse resp;

        public DetailListener(QaResponse resp) {
            this.resp = resp;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.qa_content_tv:
                case R.id.include_answer_tv:
                    Utils.intoQaDetailActivity(mContext, resp);
                    break;
                case R.id.user_head:
                case R.id.user_head_layout:
                    Utils.intoHeadInfoActivity(resp.accountId, mContext);
                    break;
                default:
                    break;
            }
        }

    }

    public class GridHolder {
        /**
         * 热门置顶
         */
        private TextView isTopTV;
        /**    热门置顶下划线	*/
//		private View isTopLine;
        /**    under划线	*/
//		private View underLine;
        /**
         * 头像
         */
        private ImageView headIV;
        /**
         * 昵称
         */
        public TextView nameTV;
        /**
         * 性别
         */
        public ImageView sexIV;
        /**
         * 标签
         */
        private TextView labelTV;
        public ImageView addV;
        /**
         * 内容
         */
        public SpanTextView contentTV;
        /**
         * 转发数
         */
        public TextView forwardTV;
        /**
         * 点赞数
         */
        public TextView praiseTV;
        /**
         * 回复数
         */
        public TextView commentTV;
        /**
         * 删除
         */
        public TextView deleteTV;
        /**
         * 浏览
         */
        public TextView visitorTV;
        /**
         * 名字，标签
         */
        private LinearLayout headInfoLayout;
        /**
         * 图片显示
         */
        private CanDoBlankGridView gridview;
    }

    public void addOneQuestData(QaResponse addData) {
        if (null != mList) {
            mList.add(topCounts, addData);
            notifyDataSetChanged();
        }
    }

    public void removeOneData(int id) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == id) {
                mList.remove(i);
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void priseNotify(int questId, int isGood, int goodCounts) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).isGood = isGood;
                mList.get(i).goodCount = goodCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void replyNotify(int questId, int answerCounts) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).answerCount = answerCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void visitorUpdate(int questId, int visitorCounts) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).visitorCount = visitorCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

}
